var utils = require('../../lib/utils');
var models = require('../Models');

var UserController = function() {
	var User = models.get('User');

	app.all('/user*', utils.restrict, function index(req, res, next) {
		next();
	});
	
	app.get('/users', function index(req, res, next) {
		User.findAll().success(function(users) {
			res.render('users/index', {users: users, userId: req.session.user.id});
		});
	});
	
	app.get('/user/new', function index(req, res, next) {
		res.render('users/index', {users: users, userId: req.session.user.id});
	});
	
	app.get('/user/:id', function index(req, res, next) {
		User.find(parseInt(req.params.id)).success(function(user) {
			if (!user) {
				res.locals.error = 'L\'utilisateur n\'existe pas ca existe pas';
				res.redirect('/users');
			} else {
				res.render('users/show', {user: user});
			}
		});
	});
	
	app.get('/user/:id/edit', function index(req, res, next) {
		User.find(parseInt(req.params.id)).success(function(user) {
			res.render('users/edit', {user: user});
		});
	});
	
	app.post('/user/:id/edit', function index(req, res, next) {
		console.log('edit');
		console.dir(req.body);

		User.find(parseInt(req.params.id)).success(function(user) {
			user.name = req.body.name;
			user.firstName = req.body.firstName;
			user.login = req.body.login;
			user.password = req.body.password;
			user.email = req.body.email;
			user.save().success(function(){
				res.locals.message = 'Mise à jour réussie';
			}).error(function(){
				res.locals.error = 'Mise à jour échouée';
			});

		});

		res.locals.error = 'L\'utilisateur n\'existe pas ca existe pas';
		res.redirect('/users');
	});
	
	app.get('/user/:id/delete', function index(req, res, next) {
		if (req.session.user.id === parseInt(req.params.id)) {
			res.locals.error = 'Vous ne pouvez pas vous supprimer !';
			res.redirect('/users');
		}
		User.find(parseInt(req.params.id)).success(function(user) {
			user.destroy().success(function() {
				res.locals.message = 'Suppréssion réussie';
				res.redirect('/users');
			});
			res.locals.error = 'Suppréssion échouée';
			res.redirect('/users');
		});
		
		res.locals.error = 'L\'utilisateur n\'existe pas ca existe pas';
		res.redirect('/users');
	});
};

module.exports = UserController;